<template>
  <div class="cart-body" v-if="this.list.length !== 0">
    <div class="body-header">
      <div class="total-items">
        <span class="text" :value="flag" v-if="flag">共{{this.list.length}}件商品</span>
        <span class="text" :value="flag" v-if="flag == false">已选中{{this.result.length}}件商品</span>
      </div>
      <span class="item-edit" :value="flag" v-if="flag" @click="edit">编辑</span>
      <span class="item-edit" :value="flag" v-if="flag === false" @click="editFinish">完成</span>
    </div>
    <div class="cart-items">
      <van-checkbox-group v-model="result" ref="checkboxGroup">
        <van-checkbox v-for="(item, index) in list" :key="index" :name="item.cart_item_id">
          <van-card :num="item.goods_count" :price="item.unit_price" :desc="getDesc(item.goods_id)"
            :title="getTitle(item.goods_id)" thumb="https://img01.yzcdn.cn/vant/ipad.jpeg">
            <template #tags>
              <van-tag plain type="danger">标签</van-tag>
              <van-tag plain type="danger">标签</van-tag>
            </template>
            <template #footer>
              <van-button size="small" @click="subtraction(item)">-</van-button>
              <van-button size="small" @click="addition(item)">+</van-button>
            </template>
          </van-card>
        </van-checkbox>
      </van-checkbox-group>

    </div>
    <div class="footer">
      <van-submit-bar :value="flag" v-if="flag" :price="sumPrice" button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="checked" @click="checkAll">全选</van-checkbox>
      </van-submit-bar>
      <van-submit-bar :value="flag" v-if="flag == false" button-text="删除" @submit="deleteItem">
        <van-checkbox v-model="checked" @click="checkAll">全选</van-checkbox>
      </van-submit-bar>
    </div>
  </div>
  <div class="cart-body" v-else>
    <div class="empty-body">
      <ul>
        <li><img src="../../../components/img/cart.png"></li>
        <li>
          <span>购物车空空如也，去逛逛吧~</span>
        </li>
      </ul>
    </div>
    <div class="empty-seckill">
      <van-divider :style="{ color: '#808A87', borderColor: '#C0C0C0', padding: '0 16px' }">商品秒杀</van-divider>
      <seckill></seckill>
    </div>
    <div class="empty-like">
      <van-divider :style="{ color: '#808A87', borderColor: '#C0C0C0', padding: '0 16px' }">你可能还喜欢</van-divider>
      <goods-list-item></goods-list-item>
    </div>
  </div>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import Seckill from '../../Home/base/Seckill.vue'
  import GoodsListItem from '../../../components/goods/GoodsListItem.vue'
  export default {
    components: {
      Seckill,
      GoodsListItem
    },
    // 调用刷新
    inject: ['reload'],
    data() {
      return {
        // 是否选中
        checked: false,
        // 选中的商品
        result: [],
        // 选中的商品的ID
        goodsIDList: [],
        flag: true
        // 购物车商品信息
        // list: []
      }
    },
    filters: {
      // 价格过滤
      priceFilter(value) {
        return value * 100
      }
    },
    methods: {
      ...mapMutations(['SET_CART', 'SET_CART_COUNT', 'SET_GOODS_ITEM']),
      // 商品描述
      getDesc(id) {
        const info = this.goodsInfo.filter(value => {
          return value.goods_id === id
        })
        return info[0].goods_name + info[0].goods_intro
      },
      // 商品标题
      getTitle(id) {
        const info = this.goodsInfo.filter(value => {
          return value.goods_id === id
        })
        return info[0].goods_name
      },
      // 减少商品数量
      subtraction(value) {
        if (value.goods_count > 1) {
          value.goods_count -= 1
          const params = {
            goods_count: value.goods_count
          }
          this.$api.homeData.updateCart(value.cart_item_id, params).then(res => {
            console.log('res:', res)
          })
        } else if (value.goods_count === 1) {
          this.$toast('该件商品1件起售')
        }
      },
      // 商品数量添加
      addition(value) {
        value.goods_count += 1
        const params = {
          goods_count: value.goods_count
        }
        this.$api.homeData.updateCart(value.cart_item_id, params).then(res => {
          console.log('res:', res)
        })
      },
      // 全选
      checkAll() {
        if (this.result.length === this.list.length) {
          this.$refs.checkboxGroup.toggleAll()
        } else {
          this.$refs.checkboxGroup.toggleAll(true)
        }
      },
      getGoodsID(val) {
        const list = this.shopCart.filter(value => {
          return value.cart_item_id === Number(val)
        })
        this.goodsIDList.push({
          goodsID: list[0].goods_id,
          count: list[0].goods_count
        })
      },
      // 提交
      onSubmit() {
        if (this.result.length === 0) {
          this.$toast('请选择商品！')
        } else {
          for (var i in this.result) {
            this.getGoodsID(this.result[i])
          }
          this.SET_GOODS_ITEM(this.goodsIDList)
          this.$router.push({
            path: '/OrderConfirm'
          })
        }
      },
      // 点击编辑
      edit() {
        this.flag = false
      },
      // 编辑完成
      editFinish() {
        this.flag = true
      },
      // 点击删除
      deleteItem() {
        for (var i in this.result) {
          this.$api.homeData.deleteCart(this.result[i]).then(res => {
            console.log('res:', res)
          })
        }
        this.reload()
      },
      // 获取购物车信息
      async getCart() {
        await this.$api.homeData.cart().then(res => {
          this.SET_CART(res.data)
        })
      },
      setCartCount() {
        this.SET_CART_COUNT(this.list.length)
      }
    },
    created() {
      this.getCart()
    },
    mounted() {
      this.setCartCount()
    },
    computed: {
      ...mapState(['shopCart', 'loginToken', 'goodsInfo']),
      // 该用户购物车列表
      list() {
        return this.shopCart.filter(value => {
          return value.user_id === this.loginToken.userId
        })
      },
      // 获得选中商品的总价
      sumPrice() {
        if (this.result.length === 0) {
          return 0
        } else {
          const info = []
          for (const i in this.list) {
            for (const j in this.result) {
              if (this.list[i].cart_item_id === this.result[j]) {
                info.push(this.list[i])
              }
            }
          }
          return info.reduce((total, num) => {
            return total + num.goods_count * num.unit_price * 100
          }, 0)
        }
      }
    }
  }
</script>

<style scoped>
  .body-header {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 46px;
    border-radius: 0 0 12px 12px;
    background-color: white;
    padding: 0 8px 8px 8px;
  }

  .empty-body {
    text-align: center;
    padding-top: 60px;
    padding-bottom: 25px;
  }

  .total-items {
    position: relative;
    width: 290px;
  }

  .total-items:after {
    content: "";
    position: absolute;
    width: 1px;
    height: .5rem;
    background-color: #bfbfbf;
    top: 50%;
    right: 0;
    margin-top: -.25rem;
  }

  .text {
    font-size: 14px;
  }

  .item-edit {
    font-size: 14px;
  }

  .van-checkbox-group .van-checkbox {
    margin-top: 14px;
    background-color: white;
    border-radius: 12px;
    padding-left: 12px;
  }

  .cart-items {
    padding-bottom: 150px;
  }

  /deep/.van-checkbox__label {
    flex: 1;
  }

  .footer {
    position: fixed;
  }

  .van-submit-bar__bar {
    justify-content: space-between;
  }

  .van-submit-bar {
    bottom: 50px;
  }
</style>
